//
//  ViewController.m
//  easyTaxi
//
//  Created by ellenpage on 12-11-26.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Constant.h"
#import "GetAreaCode.h"
#import "SocketObject.h"
#import "PassValueClass.h"
#import "RequestCMD.h"
#import <CoreLocation/CoreLocation.h>
#import "ViewController.h"
#import "RequestTaxiView.h"
#import "XMLWriter.h"
#import "NearDriverView.h"
#import "GetPhoneInfo.h" 
#import "PassMapValue.h"
#import "BMapKit.h"
#import "BMKMapView.h"
#import "SystemInfoView.h"
#import "ConfirmAddressView.h"
#import <QuartzCore/QuartzCore.h> //导入框架
#import "SysViewObject.h"
#import <MessageUI/MessageUI.h>
#import "UserShareVC.h"
#import "MacroClass.h"
#import <icallPlugin/plugin.h>
#import "GpsClass.h"
#import "ChooseAddressView.h"


BOOL isCallTheTaxi;//是否叫了出租车

BOOL isAtNanJing; //是否在南京

CGRect btnRect = CGRectMake(90, iP5 ? 454 : 371, 140, 40);

CGRect timeoutViewRect = CGRectMake(0, iP5 ? 410 : 327, 320, 42);

@interface ViewController ()<BMKMapViewDelegate,BMKGeneralDelegate,BMKSearchDelegate,BMKAnnotation,UIAlertViewDelegate,SocketDelegate,GetAddressDelegate,MFMessageComposeViewControllerDelegate,ChooseAddressViewDelegate>

@property (retain, nonatomic) NSTimer *orderTimer;  //检测天泽是否接单了
@property (retain, nonatomic) NSTimer *timeOutTimer;//超时定时器
@property (retain, nonatomic) NSTimer *fiveMinTimer;//五分钟内禁止打车定时器

@property (retain, nonatomic) NSTimer *oneMinTimer;
@property (assign, nonatomic) NSInteger i;


@property (retain, nonatomic) BMKMapView          *mapView;
@property (retain, nonatomic) BMKSearch           *searchWidget;
@property (retain, nonatomic) BMKPointAnnotation  *myPosition;  //自己位置标注
@property (retain, nonatomic) BMKSearch           *belong;      //根据坐标 逆地理编码
@property (retain, nonatomic) BMKSearch           *distanceSearch;

@property (weak, nonatomic) IBOutlet UIButton *cancelTaxiBtn;

@property (retain, nonatomic) NearDriverView *nearDriverView;

@property (weak, nonatomic) IBOutlet UIView *getOrderView;//司机已经接单本地要展示的view

@property (weak, nonatomic) IBOutlet UILabel *driverNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *carNoLbl;
@property (weak, nonatomic) IBOutlet UILabel *carColorLbl;
@property (weak, nonatomic) IBOutlet UILabel *driverCreditLbl;
@property (weak, nonatomic) IBOutlet UILabel *cardistanceLbl;

@property (weak, nonatomic) IBOutlet UILabel *driverNameLbl2;
@property (weak, nonatomic) IBOutlet UILabel *carStatusLbl;
@property (weak, nonatomic) IBOutlet UILabel *carNoLbl2;
@property (weak, nonatomic) IBOutlet UILabel *carColorLbl2;
@property (weak, nonatomic) IBOutlet UILabel *driverCreditLbl2;
@property (weak, nonatomic) IBOutlet UILabel *driverGoodValueLbl;
@property (weak, nonatomic) IBOutlet UILabel *driverBadValueLbl;

@property (weak, nonatomic) IBOutlet UIButton *userStatusBtn;
@property (strong, nonatomic) RequestTaxiView *requestView;
@property (strong, nonatomic) IBOutlet UIView *detaiView;
@property (weak, nonatomic) IBOutlet UIView *detaiView_Small;

@property (weak, nonatomic) IBOutlet UIButton *callTaxiBtn;

@property (weak, nonatomic) IBOutlet UIView *jiaoYanMaView;
@property (weak, nonatomic) IBOutlet UILabel *jiaoYanMaLbl;
@property (weak, nonatomic) IBOutlet UIView *timeoutView;
@property (weak, nonatomic) IBOutlet UILabel *timeoutLbl;

@property (strong, nonatomic) ChooseAddressView *chooseAddressView;

- (IBAction)removeThisView;

- (IBAction)zoomIn;
- (IBAction)zoomOut;
- (IBAction)showCenter;
- (IBAction)callTheTaxi;
- (IBAction)cancelTheTaxi;

//上面导航栏
- (IBAction)refresh;
- (IBAction)addNearDriverView;
- (IBAction)addInfoCenterView;

//司机接单之后的处理状态
- (IBAction)callTheDriver;     //呼叫司机
- (IBAction)confirmTaxiRequest;//已经上车

//呼叫地图上的司机
- (IBAction)callTheDriverOnMap:(UIButton *)sender;

//推荐按钮
@property (weak, nonatomic) IBOutlet UIButton *shareBtn;
//打开推荐页面
- (IBAction)openShareView;

@end

@interface UIImage(InternalMethod)

- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees;

@end

BOOL isRetina = FALSE;

@implementation UIImage(InternalMethod)

- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees
{
	CGSize rotatedSize = self.size;
	if (isRetina) {
		rotatedSize.width *= 2;
		rotatedSize.height *= 2;
	}
	UIGraphicsBeginImageContext(rotatedSize);
	CGContextRef bitmap = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
	CGContextRotateCTM(bitmap, degrees * M_PI / 180);
	CGContextRotateCTM(bitmap, M_PI);
	CGContextScaleCTM(bitmap, -1.0, 1.0);
	CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
	UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}

@end

@interface RouteAnnotation : BMKPointAnnotation
{
	int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘
	int _degree;
}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation RouteAnnotation

@synthesize type   = _type;
@synthesize degree = _degree;
@end

@implementation ViewController

#pragma mark - System Function - 系统函数

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self initialMap];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(CompleteCall:)
                                                 name:@"CompleteCall"
                                               object:nil];

    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getEndAddressNoti)
                                                 name:kGetEndAddressNoti
                                               object:nil];//得到地址的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getUserCancelNoti)
                                                 name:kGetUserCancelNoti
                                               object:nil];//用户取消打车的通知

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getDriverOrderNoti)
                                                 name:kGetDriverOrderNoti
                                               object:nil];//司机接单通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getDriverCancelOrderNoti)
                                                 name:kGetDriverCancelOrderNoti
                                               object:nil];//司机取消接单通知

    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(billRestore)
                                                 name:kBillRestore
                                               object:nil];//订单恢复
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(changeTiYanCity)
                                                 name:kChangeTiYanCityNoti
                                               object:nil];//订单恢复
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(relocation)
                                                 name:kRelocation
                                               object:nil];//超时重新定位
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleLocation)
                                                 name:kHandleLocation
                                               object:nil];//手动管理地址
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [self setCancelTaxiBtn:nil];
    [self setDriverNameLbl:nil];
    [self setCarNoLbl:nil];
    [self setCarColorLbl:nil];
    [self setDriverCreditLbl:nil];
    [self setCardistanceLbl:nil];
    [self setDriverNameLbl2:nil];
    [self setCarStatusLbl:nil];
    [self setCarNoLbl2:nil];
    [self setCarColorLbl2:nil];
    [self setDriverCreditLbl2:nil];
    [self setDriverGoodValueLbl:nil];
    [self setDriverBadValueLbl:nil];
    [self setUserStatusBtn:nil];
    [self setGetOrderView:nil];
    [self setDetaiView:nil];
    [self setDetaiView_Small:nil];
    [self setCallTaxiBtn:nil];
    [self setJiaoYanMaView:nil];
    [self setJiaoYanMaLbl:nil];
    [self setShareBtn:nil];
    [self setTimeoutView:nil];
    [self setTimeoutLbl:nil];
    [self setHideZhaoCheBaoDetailBtn:nil];
    [self setCarCompanyLbl:nil];
    [super viewDidUnload];
}


- (void)relocation
{
    NSLog(@"%f--%f",_myPosition.coordinate.latitude,_myPosition.coordinate.longitude);
    bool x =  [self.belong reverseGeocode:_myPosition.coordinate];
    NSLog(@"x = %d",x);
}

- (void)handleLocation
{
    [self.view addSubview:self.chooseAddressView];
}

- (void)chooseProvince:(NSString *)province city:(NSString *)city country:(NSString *)country postcode:(NSString *)postcode
{
    [PassValueClass sharedIntance].provinceStr= province;
    [PassValueClass sharedIntance].cityStr    = city;
    [PassValueClass sharedIntance].districtStr= country;
    NSString *areaCodeStr = [GetAreaCode getAreaCode:[PassValueClass sharedIntance].provinceStr];
    [PassValueClass sharedIntance].areaCode = areaCodeStr;//获取areaCode
    NSString *startAddressStr = @"";
    [PassValueClass sharedIntance].startAddress = startAddressStr;//获取当前地址
    [self loginServer];//得到areaCode之后,登录服务器
    [self isInNanJing:[PassValueClass sharedIntance].cityStr];
}
#pragma mark - Initial Map - 初始化地图

- (void)initialMap
{    
    self.mapView = [PassMapValue sharedIntance].mapView;
    self.mapView.frame = CGRectMake(0, 0, 320, 520);

    _mapView.showsUserLocation = YES;
    [self.view insertSubview:_mapView atIndex:0];
    _mapView.delegate = self;

    _myPosition = [[BMKPointAnnotation alloc] init];
    
    _callTaxiBtn.hidden   = NO;
    _cancelTaxiBtn.hidden = YES;
    
    _getOrderView.hidden  = YES;
    _jiaoYanMaView.hidden = YES;
    _requestView = [[RequestTaxiView alloc] init];
    [self.view addSubview:_requestView];
    [_requestView setDelegate:self];
    _requestView.hidden = YES;
    
    _detaiView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65f];
    [_detaiView_Small.layer setCornerRadius:10];
    [_detaiView_Small.layer setBorderColor:[[UIColor whiteColor] CGColor]];//描边颜色
    [_detaiView_Small.layer setBorderWidth:2.0];//描边粗细
    [self.view addSubview:_detaiView];
    _detaiView.hidden = YES;
    
    _callTaxiBtn.frame   = btnRect;
    _cancelTaxiBtn.frame = btnRect;
    
    self.timeoutView.frame = timeoutViewRect;
    self.timeoutView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];
    
    self.timeoutView.hidden = YES;
    
    self.hideZhaoCheBaoDetailBtn.hidden = YES;
    
    self.chooseAddressView = [[ChooseAddressView alloc] initWithFrame:self.view.bounds];
    self.chooseAddressView.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.view addSubview:[SysViewObject sharedIntance].sysView];
    [SysViewObject sharedIntance].sysView.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    self.belong = [[BMKSearch alloc] init];
    [self.belong setDelegate:self];
}

- (void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    if (!isTiYanMoShiOk)
    {
        bool isFirstGotLocation = [PassValueClass sharedIntance].isFirstTimeLocation;
        if (!isFirstGotLocation)
        {
            _myPosition.coordinate = userLocation.coordinate;
            _myPosition.title = @"我的位置";
            [mapView addAnnotation:_myPosition];
            [mapView selectAnnotation:_myPosition animated:YES];
            
            BMKCircle* circle = [BMKCircle circleWithCenterCoordinate:userLocation.coordinate
                                                               radius:2500];
            [mapView addOverlay:circle];

            NSLog(@"%f--%f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
            bool x =  [self.belong reverseGeocode:userLocation.coordinate];
            NSLog(@"x = %d",x);

            [mapView setCenterCoordinate:userLocation.coordinate];
            
            CLLocationCoordinate2D coor;
            coor.latitude  = userLocation.coordinate.latitude;
            coor.longitude = userLocation.coordinate.longitude;
            
            BMKCoordinateSpan   theSpan;
            BMKCoordinateRegion theRegion;
            
            theSpan.latitudeDelta  = 0.05;
            theSpan.longitudeDelta = 0.05;
            
            theRegion.center = userLocation.coordinate;
            theRegion.span   = theSpan;
            
            [mapView setRegion:theRegion];
            
            CGFloat latFloat = userLocation.coordinate.latitude;
            CGFloat lonFloat = userLocation.coordinate.longitude;
            
            if (latFloat != 0.000000 && lonFloat != 0.000000)
            {
                [PassValueClass sharedIntance].isFirstTimeLocation = YES;
                NSString *lat = [NSString stringWithFormat:@"%f",latFloat];
                NSString *lng = [NSString stringWithFormat:@"%f",lonFloat];
//                NSLog(@"%@--%@",lat,lng);
                [PassValueClass sharedIntance].latStr = lat;
                [PassValueClass sharedIntance].lngStr = lng;//存经纬度
            }
            else if (latFloat == 0.00000 || lonFloat == 0.00000)
            {
                return;
            }
        }
        //非第一次进入
        else
        {
            CGFloat latFloat = userLocation.coordinate.latitude;
            CGFloat lonFloat = userLocation.coordinate.longitude;
            
            if (latFloat != 0.000000 && lonFloat != 0.000000)
            {
                NSArray *annotations = [NSArray arrayWithArray:self.mapView.annotations];
                for (BMKPointAnnotation *annotation in annotations)
                {
                    if (![[annotation title] isEqualToString:@"我的位置"])
                    {
                        _myPosition.coordinate = userLocation.coordinate;
                        _myPosition.title = @"我的位置";
                        [mapView addAnnotation:_myPosition];
                        [mapView selectAnnotation:_myPosition animated:NO];
                    }
                    else
                    {                        
                        _myPosition.coordinate = userLocation.coordinate;
                        _myPosition.title = @"我的位置";
                    }
                }
                
                [mapView setCenterCoordinate:userLocation.coordinate];

                
                NSString *lat = [NSString stringWithFormat:@"%f",latFloat];
                NSString *lng = [NSString stringWithFormat:@"%f",lonFloat];
                [PassValueClass sharedIntance].tmpLatStr = lat;
                [PassValueClass sharedIntance].tmpLngStr = lng;//存临时经纬度
                NSLog(@"%@--%@",lat,lng);
                
                _mapView.showsUserLocation = NO;
            }
        }
    }
}

- (void)onGetAddrResult:(BMKAddrInfo *)result errorCode:(int)error
{
    BMKGeocoderAddressComponent *belongabc = [result addressComponent];
    [PassValueClass sharedIntance].provinceStr= belongabc.province;
    [PassValueClass sharedIntance].cityStr    = belongabc.city;
    [PassValueClass sharedIntance].districtStr= belongabc.district;
    
    NSString *areaCodeStr = [GetAreaCode getAreaCode:[PassValueClass sharedIntance].provinceStr];
    [PassValueClass sharedIntance].areaCode = areaCodeStr;//获取areaCode
    
    NSString *startAddressStr;
    if (belongabc.streetNumber != nil)
    {
       startAddressStr  = [NSString stringWithFormat:@"%@%@%@%@%@",belongabc.province,belongabc.city,belongabc.district,belongabc.streetName,belongabc.streetNumber];
        [PassValueClass sharedIntance].streetNameStr = [NSString stringWithFormat:@"%@%@",belongabc.streetName,belongabc.streetNumber];
    }
    else
    {
        startAddressStr  = [NSString stringWithFormat:@"%@%@%@%@",belongabc.province,belongabc.city,belongabc.district,belongabc.streetName];
        [PassValueClass sharedIntance].streetNameStr = belongabc.streetName;
    }
    
    [PassValueClass sharedIntance].startAddress = startAddressStr;//获取当前地址
    
    [self loginServer];//得到areaCode之后,登录服务器
    [self isInNanJing:belongabc.city];
}

- (void)isInNanJing:(NSString *)str
{
    if ([str isEqualToString:@"南京市"])
    {
        isAtNanJing = YES;
    }
    else
    {
        isAtNanJing = NO;
    }
}

- (void)loginServer
{
    bool isFirstGotLocation = [PassValueClass sharedIntance].isFirstTimeLocation;

    NSString *lngStr  = [PassValueClass sharedIntance].lngStr;
    NSString *latStr  = [PassValueClass sharedIntance].latStr;
    NSString *cityStr = [PassValueClass sharedIntance].cityStr;
    NSString *IMSIStr = [PassValueClass sharedIntance].IMSIStr;
    
    if (lngStr != nil && latStr != nil && cityStr != nil && IMSIStr != nil && isFirstGotLocation == YES)
    {        
        [[SocketObject sharedInstance].gcdSocket connectToHost:[PassValueClass sharedIntance].ipStr onPort:[kSocketPort integerValue] error:nil];
        NSLog(@"%@",[PassValueClass sharedIntance].ipStr);
        NSString *string    = [RequestCMD requestCMD:kUserLogIn];
        NSMutableData *data = [RequestCMD getWantedData:string];
        
        [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kUserLogIn];//1001---socket写入数据
        [[SocketObject sharedInstance].gcdSocket readDataToLength:4 withTimeout:-1 tag:0];
    }
}

#pragma mark - UserInteractions - 用户交互动作

- (IBAction)removeThisView
{
    _detaiView.hidden = YES;
}

- (IBAction)zoomIn//放大
{
    [_mapView zoomIn];
    if (_mapView.zoomLevel == 18)//最大
    {
    }
}

- (IBAction)zoomOut//缩小
{
    [_mapView zoomOut];
    if (_mapView.zoomLevel == 3)//最小
    {
    }
}

- (IBAction)showCenter//居中
{
    [_mapView setCenterCoordinate:_mapView.userLocation.coordinate animated:YES];
}

- (IBAction)callTheTaxi//叫出租车
{
//    _mapView.showsUserLocation = YES;
    

    if (isTiYanMoShiOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前处在体验模式" message:@"无法使用本功能" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    else
    {
        [_mapView setCenterCoordinate:_mapView.userLocation.coordinate
                             animated:YES];//先居中
    }
    
    if (!isSokectOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"服务器未连接,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if (!isLoginOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络问题导致登录失败,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;    
    }
    
    if (!isAvaliableCityOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你所在的区域不支持我们的服务,敬请期待~"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    //3.判断是否已经绑定手机号
    NSString *isBindedStr = [PassValueClass sharedIntance].isBindedStr;
    if (isBindedStr == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"正在获取个人信息请稍后..."
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if ([isBindedStr isEqualToString:@"0"])
    {
        if (!kIsIphone)
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"检测到您的设备不具备短信和运营商电话功能,请使用iPhone体验本程序~"
                                                                      message:nil
                                                                     delegate:self
                                                            cancelButtonTitle:@"知道了"
                                                            otherButtonTitles:nil, nil];
            
            [signUpAlertView show];
            return;
        }
        else
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"手机注册"
                                                                      message:@"为了您的交易安全,请发送一条短信,完成注册"
                                                                     delegate:self
                                                            cancelButtonTitle:@"稍后再试"
                                                            otherButtonTitles:@"发送短信", nil];
            
            signUpAlertView.tag = kUserLogInAlert;
            [signUpAlertView show];
            return;
        }
    }
    
    //3.判断起始地址是否已经获得
    
    NSString *startStr = [PassValueClass sharedIntance].startAddress;
    if (startStr == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"定位错误"
                                                        message:@"没得到您当前的位置,请打开网络,并刷新"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"刷新位置", nil];
        alert.tag = kNoStartAddressAlert;
        [alert show];
        return;
    }
    
        [_requestView initialData];
        _requestView.hidden = NO;
        [PassValueClass sharedIntance].voiceNumber = 0;
        
        [YouMengEvent YouMengEvent:kRequest_YouMeng];
}

- (IBAction)cancelTheTaxi//取消打车
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定取消打车吗?本订单信息将被删除"
                                                    message:@"注意:如果司机已经接单,打车豆将不会返还"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    alert.tag = kUserCancelAlert;
    [alert show];
}


- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
	if ([overlay isKindOfClass:[BMKPolyline class]])
    {
        BMKPolylineView *polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.tag = 10;
        polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    
    if ([overlay isKindOfClass:[BMKCircle class]])
    {   BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor   = [[UIColor darkTextColor] colorWithAlphaComponent:0.02];
        circleView.strokeColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.03];
        circleView.lineWidth = 1.0;
        return circleView;
    }
	return nil;
}


- (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(RouteAnnotation*)routeAnnotation
{
	BMKAnnotationView* view = nil;
	switch (routeAnnotation.type)
    {
		case 0:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
			if (view == nil)
            {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"];
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_start.png"]];
				view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 1:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
			if (view == nil)
            {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"];
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_end.png"]];
				view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 2:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"];
			if (view == nil)
            {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"bus_node"];
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_bus.png"]];
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 3:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"];
			if (view == nil)
            {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"rail_node"];
				view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_rail.png"]];
				view.canShowCallout = TRUE;
			}
			view.annotation = routeAnnotation;
		}
			break;
		case 4:
		{
			view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
			if (view == nil)
            {
				view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
				view.canShowCallout = TRUE;
			}
            else
            {
				[view setNeedsDisplay];
			}
			
			UIImage *image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
			view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
			view.annotation = routeAnnotation;
			
		}
			break;
		default:
			break;
	}
	
	return view;
}

- (NSString*)getMyBundlePath1:(NSString *)filename
{
	
	NSBundle * libBundle = kMYBUNDLE ;
	if ( libBundle && filename )
    {
		NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
		return s;
	}
	return nil ;
}

- (void)onGetDrivingRouteResult:(BMKPlanResult *)result errorCode:(int)error
{
    if (error == BMKErrorOk)
    {
		BMKRoutePlan* plan    = (BMKRoutePlan*)[result.plans objectAtIndex:0];
		RouteAnnotation* item = [[RouteAnnotation alloc] init];
		item.coordinate = result.startNode.pt;
		item.title = @"起点";
		item.type = 0;
		[_mapView addAnnotation:item];
		
		int index = 0;
		int size = [plan.routes count];
		for (int i = 0; i < 1; i++)
        {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++)
            {
				int len = [route getPointsNum:j];
				index += len;
			}
		}
		BMKMapPoint *points = new BMKMapPoint[index];
		index = 0;		
		for (int i = 0; i < 1; i++)
        {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++) {
				int len = [route getPointsNum:j];
				BMKMapPoint* pointArray = (BMKMapPoint*)[route getPoints:j];
				memcpy(points + index, pointArray, len * sizeof(BMKMapPoint));
				index += len;
			}
			size = route.steps.count;
			for (int j = 0; j < size; j++) {
				BMKStep* step = [route.steps objectAtIndex:j];
				item = [[RouteAnnotation alloc]init];
				item.coordinate = step.pt;
				item.title = step.content;
				item.degree = step.degree * 30;
				item.type = 4;
				[_mapView addAnnotation:item];
			}
		}		
		item = [[RouteAnnotation alloc]init];
		item.coordinate = result.endNode.pt;
		item.type = 1;
		item.title = @"终点";
		[_mapView addAnnotation:item];
        
		BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:points count:index];
		[_mapView addOverlay:polyLine];
		delete []points;
        
        NSArray *okok=result.plans;
        BMKRoutePlan *koko=[okok objectAtIndex:0];
        NSInteger distance= koko.distance;//距离目的地的距离
        [PassValueClass sharedIntance].distance = distance;
        
        BMKPoiInfo *tmpPoi = [PassValueClass sharedIntance].poi;
        NSString *endAddressStr = tmpPoi.name;

        NSString *show_dis  = [NSString stringWithFormat:@"目的地：%@ \n 估算距离：%d 公里",endAddressStr,distance/1000];
        UIAlertView *alert2 = [[UIAlertView alloc]initWithTitle:@"已选择目的地"
                                                        message:show_dis
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"提交",nil];
        alert2.tag = kGetRouteAlert;
        [alert2 show];
	}
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络错误"
                                                        message:@"没能得到路径,请检查网络,再试一次"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"重试", nil];
        alert.tag = kNoRouteAlert;
        [alert show];
    }
}


- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[RouteAnnotation class]])
    {
		return [self getRouteAnnotationView:_mapView viewForAnnotation:(RouteAnnotation*)annotation];
	}

    static NSString *AnnotationViewID = @"annotationViewID";
    
    BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    if (annotationView == nil)
    {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    if ([annotation.title isEqualToString:@"我的位置"])
    {
        
        ((BMKPinAnnotationView *)annotationView).pinColor    = BMKPinAnnotationColorRed;//标注呈绿色样式
        ((BMKPinAnnotationView*)annotationView).animatesDrop = NO;

    }
    
    if ([annotation.title isEqualToString:@"接单的司机"])
    {
        annotationView.image = mLoadImg(@"driver_purple.png");
        [_mapView selectAnnotation:annotation animated:YES];//让标注处于弹出气泡框的状态
    }
    
    if ([annotation.title isEqualToString:@"空车司机"])
    {
        annotationView.image = mLoadImg(@"driver_green.png");
        [_mapView selectAnnotation:annotation animated:YES];//让标注处于弹出气泡框的状态
    }
    
    if ([annotation.title isEqualToString:@"载客司机"])
    {
        annotationView.image = mLoadImg(@"driver_purple.png");
        [_mapView selectAnnotation:annotation animated:YES];//让标注处于弹出气泡框的状态
    }
    
    if ([annotation.title isEqualToString:@"接单司机"])
    {
        annotationView.image = mLoadImg(@"driver_purple.png");
        [_mapView selectAnnotation:annotation animated:YES];//让标注处于弹出气泡框的状态
    }
    
    if ([annotation.title isEqualToString:@"司机"])
    {
        annotationView.image = mLoadImg(@"driver_green.png");
        [_mapView selectAnnotation:annotation animated:YES];//让标注处于弹出气泡框的状态
    }

    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));//不知道干什么用的
    annotationView.annotation = annotation;//绑定对应的标点经纬度
    annotationView.canShowCallout = TRUE;  //允许点击弹出气泡框

    return annotationView;
}


- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
    NSString *titleStr = [view .annotation title];
    if ([titleStr isEqualToString:@"空车司机"] || [titleStr isEqualToString:@"载客司机"]||[titleStr isEqualToString:@"司机"])
    {
        NSInteger i = [[view.annotation subtitle] intValue] - 1;
        NSString *str = [NSString stringWithFormat:@"%d",i];
        [self showDetails:str];
    }
}

#pragma mark - 上面导航栏三个按钮

//刷新
- (IBAction)refresh
{
    _mapView.showsUserLocation = YES;

    [_mapView setCenterCoordinate:_mapView.userLocation.coordinate animated:YES];
    [self removePins];//清楚地图的点
    [self searchDrivers];//刷新司机数据
}

- (void)removePins
{
    NSArray *annotations = [NSArray arrayWithArray:_mapView.annotations];
    for (BMKPointAnnotation *annotation in annotations)
    {
        if (![[annotation title] isEqualToString:@"我的位置"])
        {
            [self.mapView removeAnnotation:annotation];
        }
    }
}

- (void)searchDrivers
{
    [[PassValueClass sharedIntance].nearDriversArrsy removeAllObjects];
    NSString *string1011 = [RequestCMD requestCMD:kNearDrivers];
    NSMutableData *dataToSend1011 = [RequestCMD getWantedData:string1011];
    [[SocketObject sharedInstance].gcdSocket writeData:dataToSend1011 withTimeout:-1 tag:kNearDrivers];
}

//加载司机列表
- (IBAction)addNearDriverView
{
    NearDriverView *tmpView = [[NearDriverView alloc] init];
    [self.view addSubview:tmpView];
}

//加载信息中心
- (IBAction)addInfoCenterView
{
    if ([SysViewObject sharedIntance].sysView.hidden == YES)
    {
        [SysViewObject sharedIntance].sysView.hidden = NO;
    }
    else
    {
        [SysViewObject sharedIntance].sysView.hidden = YES;
    }
}

#pragma mark - AlertViewDelegate - AlertView代理

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = alertView.tag;
    switch (i) {
        case kNoStartAddressAlert:
        {
            if (buttonIndex == 1)
            {
            }
        }
            break;
            
        case kNoRouteAlert:
        {
            if (buttonIndex == 1)
            {
                [self getEndAddressNoti];
            }
        }
            break;
            
        case kGetRouteAlert://发出打车申请
        {
            if (buttonIndex == 0)
            {
                [self removeAllNotions];
                _cancelTaxiBtn.hidden = YES;
                _callTaxiBtn.hidden   = NO;
            }
            if (buttonIndex == 1)
            {
                if (isAtNanJing)//在南京
                {
                    NSString *phoneStr = [PassValueClass sharedIntance].teleNumStr;
                    NSString *nameStr  = [PassValueClass sharedIntance].nickNameStr;
                    
                    NSString *uidStr   = [PassValueClass sharedIntance].tzUidStr;
                    NSLog(@"%@",uidStr);
                    
                    if ([uidStr length] > 0)
                    {
                        [self callTheTaxiByTianZe];
                    }
                    else
                    {
                        plugin *mPlugin   = [[plugin alloc] init];
                        NSString *uidStr  =  [mPlugin registerUser:phoneStr byUserName:nameStr];
                        if ([uidStr isEqualToString:@"-1"])
                        {
                            mAlertView(@"注册失败", nil);
                            return;
                        }
                        else
                        {
                            [PassValueClass sharedIntance].tzUidStr = uidStr;
                            [self uploadTianZeUid];
                            [self callTheTaxiByTianZe];
                        }
                    }
                }
                else
                {
                    //1007---打车请求
                    NSString *string    = [RequestCMD requestCMD:kCallTaxiRequest];
                    NSMutableData *data = [RequestCMD getWantedData:string];
                    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kCallTaxiRequest];
                }
            }
        }
            break;

        case kUserCancelAlert:
        {
            if (buttonIndex == 1)
            {
                //1013---取消打车
                NSString *string    = [RequestCMD requestCMD:kUserCancelTaxi];
                NSMutableData *data = [RequestCMD getWantedData:string];
                [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kUserCancelTaxi];
            }
        }
            break;
            
        case kUserLogInAlert:
        {
            if (buttonIndex == 1)
            {
                NSString *str1 = [GetPhoneInfo getCurrentTimeStamp];
                NSString *str2 = [GetPhoneInfo getCurrentIMSI];
                NSString *contentStr = [NSString stringWithFormat:@"CODE=ETAXI,TYPE=PASSENGER,TIMESTAMPS=%@,IMSI=%@",str1,str2];

                NSString *teleNoStr = nil;
                if ([PassValueClass sharedIntance].messageGatewayNoStr != nil)
                {
                    teleNoStr = [PassValueClass sharedIntance].messageGatewayNoStr;
                }
                else
                {
                    teleNoStr = kSignUpNo;
                }
                NSArray *arrry = [NSArray arrayWithObject:teleNoStr];
                
                NSLog(@"%@",arrry);

                [self sendSMS:contentStr recipientList:arrry];
                                
                MBProgressHUD *HD = [[MBProgressHUD alloc] initWithView:self.view];
                
                [self.view addSubview:HD];

                HD.labelText = @"正在注册,请耐心等待!";
                [HD showAnimated:YES whileExecutingBlock:
                 ^{
                    //对话框显示时需要执行的操作
                    sleep(10);
                 }
                 completionBlock:^{[HD removeFromSuperview];}];
                [YouMengEvent YouMengEvent:kLogin_YouMeng];
            } 
        }
            break;
            
        case kTimeoutAlert:
        {
            self.timeoutView.hidden = YES;

            [_timeOutTimer invalidate];
            _timeOutTimer = nil;

            if (buttonIndex == 1)
            {
                [self callTheTaxiByTianZe];
            }
            else if (buttonIndex == 0)
            {
                [self removeAllNotions];
                [self refresh];
                self.callTaxiBtn.hidden = NO;
                [self.callTaxiBtn removeTarget:self
                                        action:@selector(fiveMinTimeAlert)
                              forControlEvents:UIControlEventTouchUpInside];
                
                [self.callTaxiBtn addTarget:self
                                     action:@selector(callTheTaxi)
                           forControlEvents:UIControlEventTouchUpInside];

            }
        }
            break;
    
        case kNoCarAlert:
        {
            [_timeOutTimer invalidate];
            _timeOutTimer = nil;
            
            self.timeoutView.hidden = YES;
            
            if (buttonIndex == 1)
            {
                [self callTheTaxiByTianZe];
            }
            else if (buttonIndex == 0)
            {
                [self removeAllNotions];
                [self refresh];
                self.callTaxiBtn.hidden = NO;
                [self.callTaxiBtn removeTarget:self
                                        action:@selector(fiveMinTimeAlert)
                              forControlEvents:UIControlEventTouchUpInside];
                
                [self.callTaxiBtn addTarget:self
                                     action:@selector(callTheTaxi)
                           forControlEvents:UIControlEventTouchUpInside];

            }
        }
            break;
            
        case kHideZhaoCheBaoAlert:
        {

            if (buttonIndex == 1)
            {
                self.getOrderView.hidden = YES;
                [self removeAllNotions];
                [self refresh];
                
                self.callTaxiBtn.hidden = NO;
                [self.callTaxiBtn removeTarget:self
                                        action:@selector(fiveMinTimeAlert)
                              forControlEvents:UIControlEventTouchUpInside];
                
                [self.callTaxiBtn addTarget:self
                                     action:@selector(callTheTaxi)
                           forControlEvents:UIControlEventTouchUpInside];
            }
        }
            break;

        default:
            break;
    }
}

- (void)removeAllNotions
{
    NSArray *annotations = [NSArray arrayWithArray:_mapView.annotations];
    for (BMKPointAnnotation *annotation in annotations)
    {
        if (![[annotation title] isEqualToString:@"我的位置"])
        {
            [self.mapView removeAnnotation:annotation];
        }
    }
    
    NSArray *lineArray = [NSArray arrayWithArray:_mapView.overlays];
    for (BMKPolyline *view in lineArray)
    {
        if (![view isKindOfClass:[BMKCircle class]])
        {
            [self.mapView removeOverlay:view];
        }
    }
}

#pragma mark - Noti - 系统通知

- (void)getEndAddressNoti
{
    _cancelTaxiBtn.hidden = NO;
    
    if (!self.distanceSearch)
    {
        _distanceSearch = [[BMKSearch alloc] init];
    }
    NSString *cityStr = [PassValueClass sharedIntance].cityStr;
    CLLocationCoordinate2D startCoordinate;
    startCoordinate.longitude = [[PassValueClass sharedIntance].lngStr floatValue];
    startCoordinate.latitude  = [[PassValueClass sharedIntance].latStr floatValue];
    
    BMKPlanNode *startNode=[[BMKPlanNode alloc] init];
    startNode.pt   = startCoordinate;
    
    BMKPoiInfo *tmpPoi = [PassValueClass sharedIntance].poi;
    NSString *endAddressStr = tmpPoi.name;
    
    BMKPlanNode *endNode = [[BMKPlanNode alloc]  init];
    endNode.name = endAddressStr;
    endNode.pt   = tmpPoi.pt;
    
    _distanceSearch.delegate = self;
    [_distanceSearch drivingSearch:cityStr startNode:startNode endCity:cityStr endNode:endNode];
}

- (void)removeRequestView
{
    [_requestView initialData];
    _requestView.hidden = YES;
}

- (void)getAddress
{
    _callTaxiBtn.hidden   = YES;
    _cancelTaxiBtn.hidden = YES;
    
    if (!self.distanceSearch)
    {
        _distanceSearch = [[BMKSearch alloc] init];
    }
    
    NSString *cityStr = [PassValueClass sharedIntance].cityStr;
    CLLocationCoordinate2D startCoordinate;
    startCoordinate.longitude = [[PassValueClass sharedIntance].lngStr floatValue];
    startCoordinate.latitude  = [[PassValueClass sharedIntance].latStr floatValue];
    
    BMKPlanNode *startNode=[[BMKPlanNode alloc]init];
    startNode.pt   = startCoordinate;
    
    BMKPoiInfo *tmpPoi = [PassValueClass sharedIntance].poi;
    NSString *endAddressStr = tmpPoi.name;
    
    BMKPlanNode *endNode=[[BMKPlanNode alloc] init];
    endNode.name = endAddressStr;
    endNode.pt   = tmpPoi.pt;
    
    _distanceSearch.delegate = self;
    [_distanceSearch drivingSearch:cityStr startNode:startNode endCity:cityStr endNode:endNode];
}


- (void)getUserCancelNoti//用户取消打车/或者结单状态
{
    [self removeAllNotions];
    _getOrderView.hidden  = YES;
    _jiaoYanMaView.hidden = YES;
    _cancelTaxiBtn.hidden = YES;
    [PassValueClass sharedIntance].orderNO = nil;
    
    _callTaxiBtn.hidden = NO;
    [self requestDaCheDou];
}

-(void)getDriverOrderNoti
{
    _getOrderView.hidden  = NO;
    _jiaoYanMaView.hidden = NO;
    _jiaoYanMaLbl.text    = [PassValueClass sharedIntance].checkNoStr;
    
    NSString *driverNameStr   = [PassValueClass sharedIntance].nickName_Driver;
    NSString *carNoStr        = [PassValueClass sharedIntance].carNumer_Driver;
    NSString *carColorStr     = [PassValueClass sharedIntance].carColor_Driver;
    NSString *driverCreditStr = [PassValueClass sharedIntance].credit_Driver;
    
    CLLocationCoordinate2D driverCo;
    NSString *driver_lat      = [PassValueClass sharedIntance].lat_Driver;
    NSString *driver_lng      = [PassValueClass sharedIntance].lng_Driver;
    driverCo.latitude  = [driver_lat floatValue];
    driverCo.longitude = [driver_lng floatValue];
    
    CLLocationCoordinate2D userCo;
    NSString *user_lat = [PassValueClass sharedIntance].tmpLatStr;
    NSString *user_lng = [PassValueClass sharedIntance].tmpLngStr;
    userCo.latitude    = [user_lat floatValue];
    userCo.longitude   = [user_lng floatValue];
    
    double dis = [self getCLLocationDistance:userCo TheTowCoordinate:driverCo]/1000;
    NSString *disStr = [NSString stringWithFormat:@"%f",dis];
    
    NSString *newStr;
    if ([disStr length] > 6)
    {
        newStr = [disStr substringToIndex:5];
        _cardistanceLbl.text  = [newStr stringByAppendingFormat:@"公里"];
    }
    else
    {
        _cardistanceLbl.text  = [disStr stringByAppendingFormat:@"公里"];
    }
    _driverNameLbl.text = driverNameStr;
    _carNoLbl.text      = carNoStr;
    _carColorLbl.text   = carColorStr;
    _driverCreditLbl.text = driverCreditStr;
}


- (CLLocationDistance)getCLLocationDistance:(CLLocationCoordinate2D)coordinateA TheTowCoordinate:(CLLocationCoordinate2D )coordinateB
{
    CLLocationDistance dis;
    dis = BMKMetersBetweenMapPoints(BMKMapPointForCoordinate(coordinateA), BMKMapPointForCoordinate(coordinateB)) ;
    return dis;
}

- (void)getDriverCancelOrderNoti
{
    [self removeAllNotions];
    _getOrderView.hidden  = YES;
    _cancelTaxiBtn.hidden = YES;
    _jiaoYanMaView.hidden = YES;
    [PassValueClass sharedIntance].orderNO = nil;
    
    _callTaxiBtn.hidden = NO;
    [self requestDaCheDou];
}


- (void)changeTiYanCity
{
    if (!isTiYanMoShiOk)
    {
        MBProgressHUD *HD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HD];
        HD.labelText = @"退出体验模式,回到当前城市";
        [HD showAnimated:YES whileExecutingBlock:^{
            //对话框显示时需要执行的操作
            sleep(2);
        } completionBlock:^{[HD removeFromSuperview];}];
        
//        _mapView.showsUserLocation = YES;
        [_mapView setCenterCoordinate:_mapView.userLocation.coordinate
                             animated:YES];//先居中

    }
    else
    {
        MBProgressHUD *HD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HD];
        HD.labelText = @"进入体验模式";
        [HD showAnimated:YES whileExecutingBlock:^{
            //对话框显示时需要执行的操作
            sleep(2);
        } completionBlock:^{[HD removeFromSuperview];}];

        CLLocationCoordinate2D myCoordinate;
        myCoordinate.latitude  = [[PassValueClass sharedIntance].latStr_TiYanMoShi floatValue];
        myCoordinate.longitude = [[PassValueClass sharedIntance].lngStr_TiYanMoShi floatValue];
//        _mapView.showsUserLocation = YES;
        [_mapView setCenterCoordinate:myCoordinate animated:YES];
    }
}

#pragma mark - InteractionsWithDriver - 与司机的动作(接单之后/未接单)

- (IBAction)callTheDriver
{
    if (isAtNanJing)
    {
        NSString *phoneStr = [PassValueClass sharedIntance].teleNumStr;
        NSString *suidStr  = [[PassValueClass sharedIntance].zhaoCheBaoDict objectForKey:kTid];
        plugin *mPlugin    = [[plugin alloc] init];
        [mPlugin callVehicle:phoneStr bySuid:suidStr];
    }
    else
    {
        NSString *phoneNum = [PassValueClass sharedIntance].phone_Driver;// 电话号码
        NSLog(@"%@",phoneNum);
        if (phoneNum.length > 0 && [phoneNum length] == 11)
        {
            UIWebView*callWebview =[[UIWebView alloc] init];
            NSString *str = [NSString stringWithFormat:@"tel:%@",phoneNum];
            NSURL *telURL =[NSURL URLWithString:str];// 貌似tel:// 或者 tel: 都行
            [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
            [self.view addSubview:callWebview];

            [YouMengEvent YouMengEvent:kCallDriverJieDan_YouMeng];
        }
    }
}

- (IBAction)confirmTaxiRequest
{
    //1049---用户结单
    NSString *string    = [RequestCMD requestCMD:kBillFinish];
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kBillFinish];
}


#pragma mark - ShowMap's Driver - 显示地图上的司机

- (void)showDetails:(NSString *)string
{
    _driverNameLbl2.text = nil;
    _carStatusLbl.text   = nil;
    _carNoLbl2.text      = nil;
    _driverCreditLbl2.text   = nil;
    _driverGoodValueLbl.text = nil;
    _driverBadValueLbl.text  = nil;

    _detaiView.hidden = NO;
    
    NSArray *array = [PassValueClass sharedIntance].nearDriversArrsy;
    NSDictionary *dict = [array objectAtIndex:[string intValue]];
    
    _userStatusBtn.tag = [string intValue];
    
    NSString *nameStr      = [dict objectForKey:kNick];
    
    if (nameStr.length > 0)
    {
        _driverNameLbl2.text = nameStr;//司机名称
    }
    
    NSString *carStatusStr = [dict objectForKey:kStatus];
    if (carStatusStr.length == 1)
    {
        if ([carStatusStr isEqualToString:@"1"])
        {
            _carStatusLbl.text = @"空车";
            
        }
        else if ([carStatusStr isEqualToString:@"2"])
        {
            _carStatusLbl.text = @"载客";
        }
        else if ([carStatusStr isEqualToString:@"3"])
        {
            _carStatusLbl.text = @"空车";
        }

    }
    
    NSString *carNoStr = [dict objectForKey:kHPHM];
    if (carNoStr.length > 0)
    {
        _carNoLbl2.text = carNoStr;
    }
    
    NSString *driverCreditStr   = [dict objectForKey:kCredit];
    if (driverCreditStr.length > 0)
    {
        _driverCreditLbl2.text = driverCreditStr;
    }
    
    NSString *goodEvaluationStr = [dict objectForKey:kGoodEvaluate];
    if (goodEvaluationStr.length > 0)
    {
        _driverGoodValueLbl.text = goodEvaluationStr;
    }
    
    NSString *badEvaluationStr  = [dict objectForKey:kBadEvaluate];
    if (badEvaluationStr.length > 0)
    {
        _driverBadValueLbl.text = badEvaluationStr;
    }
}

- (IBAction)callTheDriverOnMap:(UIButton *)sender
{
    int i          = sender.tag;
    NSArray *array = [PassValueClass sharedIntance].nearDriversArrsy;
    NSDictionary *dict = [array objectAtIndex:i];
    
    NSString *phoneStr     = [dict objectForKey:kTelephone];//司机电话
    NSString *isTianZe     = [dict objectForKey:kIsTianZe];
    
    if ([isTianZe isEqualToString:@"0"])
    {
        if (phoneStr.length > 0 && [phoneStr length] == 11)
        {
            UIWebView*callWebview =[[UIWebView alloc] init];
            NSString *str = [NSString stringWithFormat:@"tel:%@",phoneStr];
            NSURL *telURL =[NSURL URLWithString:str];// 貌似tel:// 或者 tel: 都行
            [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
            [self.view addSubview:callWebview];
            [YouMengEvent YouMengEvent:kCallDriverOnMap_YouMeng];
        }
    }
    else if ([isTianZe isEqualToString:@"1"])
    {
        NSString *phoneStr = [PassValueClass sharedIntance].teleNumStr;
        NSString *suidStr  = [dict objectForKey:kSUID];
        plugin *mPlugin    = [[plugin alloc] init];
        [mPlugin callVehicle:phoneStr bySuid:suidStr];    
    }
}

#pragma mark - SendMMS - 发送短信

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentModalViewController:controller animated:YES];
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent");
    else
        NSLog(@"Message failed");
}

#pragma mark - BillRestore -订单恢复

- (void)billRestore
{
    [self requestDaCheDou];
    
    NSString *status = [PassValueClass sharedIntance].statusStr;
    
    NSDictionary *dict = [PassValueClass sharedIntance].billRestoreDict;
    NSLog(@"%@",dict);
    
//    NSString *statusStr    = [dict objectForKey:kStatus];
    
    NSString *phoneStr     = [dict objectForKey:kTelephone];
    NSString *latStr       = [dict objectForKey:kLatitude];
    NSString *lngStr       = [dict objectForKey:kLongitude];
    NSString *colorStr     = [dict objectForKey:kColor];
    NSString *hphmStr      = [dict objectForKey:kHPHM];
    NSString *nicknameStr  = [dict objectForKey:kNick];

    if ([status isEqualToString:@"1"])
    {
        if (_getOrderView.hidden == YES)
        {
            _callTaxiBtn.hidden   = YES;
            _cancelTaxiBtn.hidden = NO;
            _getOrderView.hidden  = NO;
            _jiaoYanMaView.hidden = NO;
            _jiaoYanMaLbl.text    = [PassValueClass sharedIntance].checkNoStr;
            
            CLLocationCoordinate2D driverCo;
            driverCo.latitude  = [latStr floatValue];
            driverCo.longitude = [lngStr floatValue];
            
            CLLocationCoordinate2D userCo;
            NSString *user_lat = [PassValueClass sharedIntance].tmpLatStr;
            NSString *user_lng = [PassValueClass sharedIntance].tmpLngStr;
            userCo.latitude    = [user_lat floatValue];
            userCo.longitude   = [user_lng floatValue];
            
            double dis = [self getCLLocationDistance:userCo TheTowCoordinate:driverCo]/1000;
            NSString *disStr = [NSString stringWithFormat:@"%f",dis];
            
            NSString *newStr;
            if ([disStr length] > 6)
            {
                newStr = [disStr substringToIndex:5];
                _cardistanceLbl.text  = [newStr stringByAppendingFormat:@"公里"];
            }
            else
            {
                _cardistanceLbl.text  = [disStr stringByAppendingFormat:@"公里"];
            }
            _driverNameLbl.text = nicknameStr;
            _carNoLbl.text      = hphmStr;
            _carColorLbl.text   = colorStr;
            
            [PassValueClass sharedIntance].phone_Driver = phoneStr;            
        }
    }
    else if ([status isEqualToString:@"0"])
    {
        UIAlertView *noDriverAlert = [[UIAlertView alloc] initWithTitle:@"检测到未接单的订单"
                                                                message:@"是否继续,可以点击取消打车按钮取消本次打车"
                                                               delegate:self
                                                      cancelButtonTitle:@"知道了"
                                                      otherButtonTitles:nil, nil];
        [noDriverAlert show];
        
        _getOrderView.hidden  = YES;
        _jiaoYanMaView.hidden = YES;
        _callTaxiBtn.hidden   = YES;
        _cancelTaxiBtn.hidden = NO;
    }
}

#pragma mark - ShareView - 分享界面

- (IBAction)openShareView
{
    [YouMengEvent YouMengEvent:kOpenShareView];

    UserShareVC *tmpShareView = [[UserShareVC alloc] init];
    [self.navigationController pushViewController:tmpShareView animated:YES];
}

#pragma mark - RequestDaCheDou - 查询打车豆

- (void)requestDaCheDou
{
    NSString *string    = [RequestCMD requestCMD:kRequetDaCheDou];
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kRequetDaCheDou];
}

#pragma mark - callTheTaxiByTianZe - 天泽

- (void)callTheTaxiByTianZe
{
    
    [self.callTaxiBtn removeTarget:self action:@selector(callTheTaxi) forControlEvents:UIControlEventTouchUpInside];
    [self.callTaxiBtn addTarget:self    action:@selector(fiveMinTimeAlert) forControlEvents:UIControlEventTouchUpInside];
    
    [self orderToTianZe];

    
    self.timeoutView.hidden = NO;
    
    if (!_timeOutTimer)
    {
        _timeOutTimer = [NSTimer scheduledTimerWithTimeInterval:150 target:self selector:@selector(restartOrCancel) userInfo:nil repeats:YES];
    }
    
    if (!_oneMinTimer)
    {
        [_oneMinTimer invalidate];
        _oneMinTimer = nil;
    }
    
    [self showTimeOut];

}

- (void)fiveMinTimeAlert
{
    mAlertView(@"您的上一次打车申请尚未处理完成,系统正在为您调度服务车辆,请勿重复发起打车申请,谢谢！", nil);
}

- (void)finishFiveMinTimer
{
    [_fiveMinTimer invalidate];
    _fiveMinTimer = nil;
    
    [self.callTaxiBtn removeTarget:self
                            action:@selector(fiveMinTimeAlert)
                  forControlEvents:UIControlEventTouchUpInside];
    
    [self.callTaxiBtn addTarget:self
                         action:@selector(callTheTaxi)
               forControlEvents:UIControlEventTouchUpInside];
}

- (void)showTimeOut
{
    if (!_oneMinTimer)
    {
        _oneMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                        target:self
                                                      selector:@selector(timeroneMethod)
                                                      userInfo:nil
                                                       repeats:YES];
    } 
    
    [self timeroneMethod];
    self.i = 150;
}

- (void)timeroneMethod
{
    self.i --;
    
    if (self.i  + 1 > 0)
    {
        self.timeoutLbl.text = [NSString stringWithFormat:@"%d",self.i];//倒计时显示
    }
}

- (void)orderToTianZe
{
    
    NSString *uidStr  = [PassValueClass sharedIntance].tzUidStr;
    NSString *nameStr = [PassValueClass sharedIntance].nickNameStr;
    
    NSLog(@"%@--%@",uidStr,nameStr);
    
    plugin *mPlugin    = [[plugin alloc] init];
    
    
    NSInteger lat;
    NSInteger lng;
    
    if ([PassValueClass sharedIntance].lon_Tianze != 0.00000 && [PassValueClass sharedIntance].lat_Tianze != 0.00000)
    {
        lat  = [PassValueClass sharedIntance].lat_Tianze * 3600000;
        lng  = [PassValueClass sharedIntance].lon_Tianze * 3600000;
    }
    else
    {
        lat   = [[PassValueClass sharedIntance].tmpLatStr  floatValue] * 3600000;
        lng   = [[PassValueClass sharedIntance].tmpLngStr  floatValue] * 3600000;
    }
    
    NSString *latStr = [NSString stringWithFormat:@"%d",lat];
    NSString *lngStr = [NSString stringWithFormat:@"%d",lng];
     
    NSString *curStr = [PassValueClass sharedIntance].streetNameStr;
    
    BMKPoiInfo *tmpPoi   = [PassValueClass sharedIntance].poi;
    NSString *desStr     = tmpPoi.name;
    
    NSString *lngStr_Des = [NSString stringWithFormat:@"%f",tmpPoi.pt.longitude];
    NSString *latStr_Des = [NSString stringWithFormat:@"%f",tmpPoi.pt.latitude];
    
    CLLocationCoordinate2D location;
    location.latitude  = [latStr_Des floatValue];
    location.longitude = [lngStr_Des floatValue];
    
    NSDictionary *dict = BMKBaiduCoorForWgs84(location);
    CLLocationCoordinate2D baiduLocation = BMKCoorDictionaryDecode(dict);
    float latTmp = baiduLocation.latitude;
    float lonTmp = baiduLocation.longitude;
    
    int finalLat = (2 * location.latitude  - latTmp) * 3600000;
    int finalLng = (2 * location.longitude - lonTmp) * 3600000;
        
    NSString *finalLatStr = [NSString stringWithFormat:@"%d",finalLat];
    NSString *finalLngStr = [NSString stringWithFormat:@"%d",finalLng];
    
//    uidStr = @"18961805998";
//    latStr = @"115361952";
//    lngStr = @"427554112";
//    curStr = @"测试出发地";
//    desStr = @"测试目的地";
//    finalLatStr = @"115517655";
//    finalLngStr = @"427649139";
//    nameStr = @"测试单";
    
    NSString *statusStr = [mPlugin getOneCall:uidStr 
                                    byFromLat:latStr
                                    byFromLon:lngStr
                                byFromAddress:curStr
                                      byToLat:finalLatStr
                                      byToLon:finalLngStr
                                  byToAddress:desStr
                                       byName:nameStr];
    
    NSLog(@"statusStr = %@",statusStr);

   if ([statusStr isEqualToString:@"1"])
    {
        [_timeOutTimer invalidate];
        _timeOutTimer = nil;        
    }
    else if ([statusStr isEqualToString:@"-1"])
    {
        mAlertView(@"系统错误", nil);
    }
}

- (void)restartOrder
{
    [self orderToTianZe];
}


- (void)restartOrCancel
{
    UIAlertView *timeOutAlert = [[UIAlertView alloc] initWithTitle:@"长时间无人接单,请问是否取消"
                                                           message:nil
                                                          delegate:self
                                                 cancelButtonTitle:@"取消订单"
                                                 otherButtonTitles:@"重新打车", nil];
    timeOutAlert.tag = kTimeoutAlert;
    [timeOutAlert show];
}

- (void)CompleteCall:(NSNotification*)notify
{
    NSDictionary *dict = [notify userInfo];
    NSLog(@"%@",dict);
    
    //0:招车失败 1:招车成功
    NSLog(@"%@", [dict objectForKey:@"state"]);
    
    NSString *statuStr = [dict objectForKey:@"state"];
    if ([statuStr isEqualToString:@"0"])
    {
        UIAlertView *noCarAlert = [[UIAlertView alloc] initWithTitle:@"招车失败,请重新再试一次~"
                                                             message:nil
                                                            delegate:self
                                                   cancelButtonTitle:@"取消招车"
                                                   otherButtonTitles:@"重新招车", nil];
        noCarAlert.tag = kNoCarAlert;
        [noCarAlert show];
    }
    else
    {
        NSString *phoneStr     = [PassValueClass sharedIntance].teleNumStr;
        NSString *cityStr      = [PassValueClass sharedIntance].cityStr;
        NSString *areaCodeStr  = [PassValueClass sharedIntance].areaCode;
        NSString *curStr       = [PassValueClass sharedIntance].startAddress;
        BMKPoiInfo *tmpPoi     = [PassValueClass sharedIntance].poi;
        NSString *desStr       = tmpPoi.name;
        
        [_timeOutTimer invalidate];
        _timeOutTimer = nil;
        
        self.timeoutView.hidden   = YES;
        self.getOrderView.hidden  = NO;
        self.jiaoYanMaView.hidden = YES;
        self.getOrderView.frame   = CGRectMake(0, 40, 320, 147);
        self.hideZhaoCheBaoDetailBtn.hidden = NO;
        self.callTaxiBtn.hidden = NO;
        
        NSString *suidStr       = [dict objectForKey:@"suid"];
        NSString *vnameStr      = [dict objectForKey:@"vname"];
        NSString *modelStr      = [dict objectForKey:@"model"];
        NSString *companyStr    = [dict objectForKey:@"company"];
        NSString *driverNameStr = [dict objectForKey:@"driverName"];
                
        NSString *latStr   = [dict objectForKey:@"lat"];
        NSString *lonStr   = [dict objectForKey:@"lon"];
        
        CLLocationCoordinate2D location;
        location.latitude  = [latStr floatValue];
        location.longitude = [lonStr floatValue];
        NSDictionary *dict = BMKBaiduCoorForWgs84(location);
        CLLocationCoordinate2D baiduLocation = BMKCoorDictionaryDecode(dict);
        float lat = baiduLocation.latitude;
        float lon = baiduLocation.longitude;
        [[PassMapValue sharedIntance] showDriverFromTianZe:lat lng:lon];
        
        self.driverNameLbl.text = driverNameStr;
        self.carNoLbl.text      = vnameStr;
        self.carCompanyLbl.text = companyStr;
        
        CLLocationCoordinate2D userCo;
        NSString *user_lat = [PassValueClass sharedIntance].tmpLatStr;
        NSString *user_lng = [PassValueClass sharedIntance].tmpLngStr;
        userCo.latitude  = [user_lat floatValue];
        userCo.longitude = [user_lng floatValue];
        
        NSString *driver_lat = [NSString stringWithFormat:@"%f",lat];
        NSString *driver_lon = [NSString stringWithFormat:@"%f",lon];
        
        double dis = [self getCLLocationDistance:userCo TheTowCoordinate:baiduLocation]/1000;
        NSString *disStr = [NSString stringWithFormat:@"%f",dis];
        
        NSString *newStr;
        if ([disStr length] > 6)
        {
            newStr = [disStr substringToIndex:5];
            self.cardistanceLbl.text  = [newStr stringByAppendingFormat:@"公里"];
        }
        else
        {
            self.cardistanceLbl.text  = [disStr stringByAppendingFormat:@"公里"];
        }
        
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:suidStr     forKey:kTid];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:phoneStr    forKey:kPhone];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:cityStr     forKey:kCity];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:areaCodeStr forKey:kAreaCode];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:@"0"        forKey:kType];
        
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:curStr     forKey:kFrom];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:desStr     forKey:kTo];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:user_lat   forKey:kFromLat];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:user_lng   forKey:kFromLon];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:driver_lat forKey:kToLat];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:driver_lon forKey:kToLon];

        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:disStr     forKey:kDistance];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:vnameStr forKey:kCarId];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:driverNameStr forKey:kDriverName];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:vnameStr forKey:kCarNo];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:modelStr   forKey:kCarType];
        [[PassValueClass sharedIntance].zhaoCheBaoDict setObject:companyStr forKey:kCompany];

        NSString *string    = [RequestCMD requestCMD:kUploadZhaoCheBaoOrder];
        NSMutableData *data = [RequestCMD getWantedData:string];
        [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kUploadZhaoCheBaoOrder];
        
        if (!_fiveMinTimer)
        {
            _fiveMinTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(finishFiveMinTimer) userInfo:nil repeats:YES];
        }
    }
}

- (void)uploadTianZeUid
{
    NSString *string    = [RequestCMD requestCMD:kUploadTianZeUid];//获取个人信息
    NSMutableData *data = [RequestCMD getWantedData:string];
    
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kUploadTianZeUid];//获取个人信息
}

- (IBAction)hideZhaoCheBaoDetailView
{
    UIAlertView *hiddenZhaoCheBaoOrderAlert = [[UIAlertView alloc] initWithTitle:@"确认隐藏该页面吗?"
                                                                         message:nil
                                                                        delegate:self
                                                               cancelButtonTitle:@"取消"
                                                               otherButtonTitles:@"确认", nil];
    hiddenZhaoCheBaoOrderAlert.tag = kHideZhaoCheBaoAlert;
    [hiddenZhaoCheBaoOrderAlert show];
}

@end
